package com.tuyue.controller;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.oauth.Oauth;
import com.tuyue.dao.IUserDao;
import com.tuyue.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static java.lang.System.out;

/**
 * @Author: 王金海
 * @Description:
 * @Date: Created by Administrator on 2018/1/3.
 * @Modified By:
 */
@Controller
public class Login {

    @Autowired
    private IUserDao userDao;

    @RequestMapping("/")
    public String login(){
        return "login";
    }

    /**
     *
     * @methodDesc: 功能描述:(生成qq授权)
     * @param: @param
     *             request
     * @param: @return
     * @param: @throws
     *             QQConnectException
     */
    @RequestMapping("/authorizeUrl")
    public String authorizeUrl(HttpServletRequest request) throws QQConnectException {
        String authorizeUrl = new Oauth().getAuthorizeURL(request);
        out.println(authorizeUrl);
        return "redirect:"+authorizeUrl;
    }

    @RequestMapping("/host")
    public ModelAndView qqLoginCallback(HttpServletRequest request, HttpServletResponse response, HttpSession httpSession,Model model) throws QQConnectException {
        // String code = request.getParameter("code");
        // 第一步获取授权码
        // 第二步获取accesstoken
        AccessToken accessTokenObj = new Oauth().getAccessTokenByRequest(request);
        String accessToken = accessTokenObj.getAccessToken();
        if (StringUtils.isEmpty(accessToken)) {
            model.addAttribute("msg","获取授权码失败");
            return new ModelAndView("error","error",model);
        }

        OpenID openidObj = new OpenID(accessToken);
        // 数据查找openid是否关联,如果没有关联先跳转到关联账号页面,如果直接登录.

        String userOpenId = openidObj.getUserOpenID();
        User user = userDao.findByOpenid(userOpenId);
        if (user==null) {
            model.addAttribute("openid",userOpenId);
            return new ModelAndView("guanlian","user",model);
        }
        return new ModelAndView("index");
    }


    @RequestMapping("/guanlian")
    public String guanlian(String userName,String openid){
        User user = new User();
        user.setOpenid(openid);
        user.setUserName(userName);
        User save = userDao.save(user);
        if (save==null){
            return "error";
        }
        return "index";
    }
}
